<template>
	<view class="z-box" :style="`padding-top:${BarNavHeight}px`">
		<u-navbar :autoBack="true" leftIconColor="#000" :title="title" :title-style="NavCss" bgColor="#f9f9f9">
			<view slot="right">
				<text v-if="isSubmit" @click="submit('save')">保存</text>
				<text v-if="isSubmit" style="margin-left: 10px" @click="submit('submit')">上报</text>
				<text v-if="isAuth">
					<!-- 状态是3 已上报时 县组长以及市组长可以审批 状态是3 采样数据已上报 4 小组已审核 5小组审核不通过省组长可以审批  -->
					<span v-if="taskInfo.taskStatus === '3'|| (taskInfo.taskStatus === '3'||taskInfo.taskStatus === '4'||taskInfo.taskStatus === '5'&& /PZZ/.test(roles))" @click="auth">审核</span>
					<!-- <span v-if="taskInfo.taskStatus === '5'" @click="auth">通过</span> -->
					<!-- <span v-if="taskInfo.taskStatus === '4'" @click="authBack">回退</span> -->
				</text>
			</view>
		</u-navbar>
		<u-tabs lineWidth="66" :current="currTabIndex"  :list="tabList" :scrollable="false" @click="switchTab"></u-tabs>
		<view v-if="inited" class="z-body" :style="`height:${NTBodyHeight}px`">
			<Task ref="taskRef" v-show="currTabIndex === 0"></Task>
			<Field ref="fieldRef" v-show="currTabIndex === 1"></Field>
			<Soil ref="soidRef" v-show="currTabIndex === 2"></Soil>
			<Crop ref="cropRef" v-show="currTabIndex === 3"></Crop>
		</view>
		 <!-- :showCancelButton='showCancel' -->
		<u-modal  cancelText="回退" confirmText="通过" showCancelButton showConfirmButton :show="showAuthModal"
			:title="`输入审核意见`" @cancel="rejectAuth" @confirm="submitAuth" @click="showAuthModal = false">
			<view class="slot-content">
				<u-textarea placeholder=" 请输入内容" style="width: 80vw;" v-model="authContent"></u-textarea>
			</view>
		</u-modal>
		<u-notify ref="notify"></u-notify>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import LayoutMix from '@/mixins/layout-mix.js'
	import NotifyMix from '@/mixins/notify-fix.js'
	import Util from '@/utils/index.js'
	import API from '@/api/index.js'
	import Task from './components/task.vue'
	import Field from './components/field.vue'
	import Soil from './components/soil.vue'
	import Crop from './components/crop.vue'
	export default {
		mixins: [LayoutMix, NotifyMix],
		components: {
			Task,
			Field,
			Soil,
			Crop
		},
		data() {
			return {
				urlParams: {
					action: '',
					taskId: '',
				},
				tabList: [{
						name: `任务`,
					},
					{
						name: '田地',
					},
					{
						name: '土壤',
					},
					{
						name: '农产品',
					}
				],
				currTabIndex: 0,
				showAuthModal: false,
				authType: '1', // 1 审核 -1 回退
				authContent: '',
				inited: false, // 用于父组件初始化完成开始初始化子组件的契机
				roles:false,
				showCancel:true,
			}
		},
		computed: {
			...mapState({
				action: state => state.cjRecord.action,
				taskInfo: state => state.cjRecord.taskInfo,
				recordInfo: state => state.cjRecord.recordInfo,
				isLT200m: state => state.cjRecord.isLT200m,
				userInfo: state => state.user.userInfo
			}),
			isZZ() {
				return this.userInfo.currentOrgPosition.positionName === '组长'
			},
			isZY() {
				return this.userInfo.currentOrgPosition.positionName === '组员'
			},
			title() {
				return this.action === 'add' ? '省控点信息采集' :
					this.taskInfo.positionType === '1' ? '国控点信息采集' :
					'省控点信息采集'
			},
			isSubmit() {
				return ['add', 'edit'].includes(this.urlParams.action)
			},
			isAuth() {
				return this.urlParams.action === 'auth'|| /PZZ/.test(this.roles)
			},
			isAuthBack() {
				return this.urlParams.action === 'back'
			}
		},
		methods: {
			...mapMutations({
				setAction: 'cjRecord/setAction',
				setTaskInfo: 'cjRecord/setTaskInfo',
				resetTaskInfo: 'cjRecord/resetTaskInfo',
				setTaskInfoAttr: 'cjRecord/setTaskInfoAttr',
				setRecordInfo: 'cjRecord/setRecordInfo',
				resetRecordIno: 'cjRecord/resetRecordIno',
				setRecordInfoAttr: 'cjRecord/setRecordInfoAttr',
				setIsLT200m: 'cjRecord/setIsLT200m',
				clearCjRecord: 'cjRecord/clearCjRecord',
			}),
			auth() {
				this.showAuthModal = true
			},
			async submit(operateType) {
				if (operateType == 'save') {
					const currentRef = [
						this.$refs.taskRef, // index 0
						this.$refs.fieldRef, // index 1
						this.$refs.soidRef, // index 2
						this.$refs.cropRef // index 3
					][this.currTabIndex];
					if (!(await currentRef.checkForm())) {
						this.notifyFail("提交失败，请检查数据");
						return;
					}
				} else if (operateType == 'submit') {
					let b1 = await this.$refs.taskRef.checkForm()
					let b2 = await this.$refs.fieldRef.checkForm()
					let b3 = await this.$refs.soidRef.checkForm()
					let b4 = await this.$refs.cropRef.checkForm()

					if (!b1 || !b2 || !b3 || !b4) {
						this.notifyFail(`提交失败，请检查数据`)
						return
					}
				}


				const form = {
					operateType: operateType,
					positionType: this.taskInfo.positionType,
					cjTaskUpdateDTO: this.taskInfo,
					cjRecordUpdateDTO: this.recordInfo
				}
				// 检查提交的经纬度是否一致
				this.taskInfo.autoLongLat = true
				uni.showLoading()
				console.log(form, 'form')
				const res = await API.CjRecordApi.addTask(form)
				uni.hideLoading()
				if (res.code !== 200 || !res.data) {
					this.notifyFail(res.message)
					return
				}
				this.notifyFail('提交成功')
				uni.navigateTo({
					url: "/pages/cj-task/cj-task"
				})
			},
			async submitAuth() {
				uni.showLoading()
				let taskStatus = ''
				if(!/PZZ/.test(uni.getStorageSync('roles'))){
					// 县 市组长审批
					let taskStatus = '4'
				}else{
					// 省组长审批
					let taskStatus = '6'
				}
				
				const res = await API.CjAuthHistoryApi.auditTask({
					taskId: this.taskInfo.id,
					recordId: this.recordInfo.id,
					opinion: this.authContent,
					taskStatus: taskStatus,
					auditType: '3',
				})
				uni.hideLoading()
				if (res.code !== 200 || !res.data) {
					this.notifyFail(res.message)
					return
				}
				this.notifyFail('操作成功')
				uni.navigateTo({
					url: "/pages/cj-task/cj-task"
				})
			},
			async rejectAuth() {
				uni.showLoading()
				let taskStatus = ''
				if(!/PZZ/.test(uni.getStorageSync('roles'))){
					// 县 市组长审批
					taskStatus = '5'
				}else{
					// 省组长审批
					taskStatus = '7'
				}
				const res = await API.CjAuthHistoryApi.auditTask({
					taskId: this.taskInfo.id,
					recordId: this.recordInfo.id,
					opinion: this.authContent,
					taskStatus: taskStatus,
					auditType: '4',
				})
				uni.hideLoading()
				if (res.code !== 200 || !res.data) {
					this.notifyFail(res.message)
					return
				}
				this.notifyFail('操作成功')
				uni.navigateTo({
					url: "/pages/cj-task/cj-task"
				})
			},
			switchTab(val) {
				this.currTabIndex = val.index
			},
			async calcIsLT200m() {
				const res = await Util.UniUtil.getLonLat()
				if (!res) {
					this.notifyFail('无法获取到点位信息')
					return
				}
				this.setIsLT200m(Util.UniUtil.isLT200m(this.taskInfo.wgs84Longitude, this.taskInfo.wgs84Latitude, res
					.wgs84.longitude, res.wgs84.latitude))
			}
		},
		onLoad(query) {
			this.urlParams.action = String(query.action)
			this.urlParams.taskId = String(query.taskId)
			console.log(query,'query')
		},
		async mounted() {
			this.roles = uni.getStorageSync('roles')
			
			this.setAction(this.urlParams.action)
			this.resetTaskInfo()
			this.resetRecordIno()
			if (this.urlParams.action === 'add') {
				this.setTaskInfoAttr({
					key: 'positionType',
					val: '2'
				})
				this.setTaskInfoAttr({
					key: 'taskStatus',
					val: '2'
				})
				const res = await API.SysDayCodeApi.getNumPlus()
				if (res.code !== 200 || !res.data) {
					this.notifyFail('获取生成码错误')
					return
				}
				const code = Util.dayjs().format('YYYYMMDD-').substring(2) + res.data
				this.setTaskInfoAttr({
					key: 'code',
					val: code
				})
				this.setRecordInfoAttr({
					key: 'soilSamplingCode',
					val: 'T-' + code
				})
				this.setRecordInfoAttr({
					key: 'cropSamplingCode',
					val: 'C-' + code
				})
			} else {
				uni.showLoading()
				const res = await API.CjTaskApi.getTaskDetail(this.urlParams.taskId)
				uni.hideLoading()
				if (res.code !== 200 || !res.data) {
					this.notifyFail('获取任务详情失败')
					return
				}
			// 	let rolesContent = 2
			// 	let rolesContentOther = ''
				
			// 	const regex = /PZZ/; 
			// 	if(regex.test(this.roles)){
			// 		rolesContentOther = 3
			// 	}else {
			// 		rolesContentOther = 1
			// 	};
			// if(rolesContentOther<rolesContent&&this.urlParams.taskStatus==3){
			// 	// 省组长
			// 	this.showCancel = false
			// }else{
			// 	this.showCancel = true
			// }
				
				this.setTaskInfo({
					"id": res.data.id,
					"projectId": res.data.projectId,
					"orgId": res.data.orgId,
					"year": res.data.year,
					"samplingType": res.data.samplingType,
					"taskStatus": res.data.taskStatus,
					"code": res.data.code,
					"positionType": res.data.positionType,
					"province": res.data.province,
					"city": res.data.city,
					"county": res.data.county,
					"town": res.data.town,
					"village": res.data.village,
					"team": res.data.team,
					"landUse": res.data.landUse,
					"wgs84Longitude": res.data.wgs84Longitude,
					"wgs84Latitude": res.data.wgs84Latitude,
					"wgs84Altitude": res.data.wgs84Altitude,
					"gcj02Longitude": res.data.gcj02Longitude,
					"gcj02Latitude": res.data.gcj02Latitude,
					"soilType": res.data.soilType,
					"protectionStrategy": res.data.protectionStrategy,
					"soilClass": res.data.soilClass,
					"subClass": res.data.subClass,
					"soilMaterial": res.data.soilMaterial,
					"mainCrop": res.data.mainCrop,
					"cropType": res.data.cropType,
					"provinceName": res.data.provinceName,
					"cityName": res.data.cityName,
					"countyName": res.data.countyName,
					"cropTypeManual": res.data.cropTypeManual,
				})
				this.setRecordInfo({
					"id": res.data.recordId,
					"projectId": res.data.projectId,
					"taskId": res.data.taskId,
					"samplingTime": res.data.samplingTime,
					"autoProvinceCityCounty": res.data.autoProvinceCityCounty,
					"autoLngLat": res.data.autoLngLat,
					"screenLongitude": res.data.screenLongitude,
					"screenLatitude": res.data.screenLatitude,
					"screenAltitude": res.data.screenAltitude,
					"nitrogen": res.data.nitrogen,
					"phosphate": res.data.phosphate,
					"potassium": res.data.potassium,
					"organic": res.data.organic,
					"compound": res.data.compound,
					"eastInfo": res.data.eastInfo,
					"southInfo": res.data.southInfo,
					"westInfo": res.data.westInfo,
					"northInfo": res.data.northInfo,
					"waterSourceInfo": res.data.waterSourceInfo,
					"disasterInfo": res.data.disasterInfo,
					"otherInfo": res.data.otherInfo,
					"eastImage": res.data.eastImage,
					"southImage": res.data.southImage,
					"westImage": res.data.westImage,
					"northImage": res.data.northImage,
					"centerGps": res.data.centerGps,
					"waterSourceImage": res.data.waterSourceImage,
					"disasterImage": res.data.disasterImage,
					"otherImage": res.data.otherImage,
					"soilSamplingCode": 'T-' + res.data.code,
					"samplingDepth": res.data.samplingDepth,
					"sampleWeight": res.data.sampleWeight,
					"soilSamplingSceneImage": res.data.soilSamplingSceneImage,
					"soilSamplePackageImage": res.data.soilSamplePackageImage,
					"soilBag2Label2Image": res.data.soilBag2Label2Image,
					"soilOtherImage": res.data.soilOtherImage,
					"cropSamplingCode": 'C-' + res.data.code,
					"cropName": res.data.cropName,
					"cropWeight": res.data.cropWeight,
					"quarterProduction": res.data.quarterProduction,
					"cropSamplingSceneImage": res.data.cropSamplingSceneImage,
					"cropSamplePackageImage": res.data.cropSamplePackageImage,
					"cropBag2Label2Image": res.data.cropBag2Label2Image,
					"cropOtherImage": res.data.cropOtherImage,
					"comment": res.data.comment
				})
				console.log(/PZZ/.test(this.roles),this.taskInfo.taskStatus,'/PZZ/.test(roles)')
				// 如果是国控点且为新增或修改，则计算离目标点的距离
				if (this.taskInfo.positionType === '1' && this.isSubmit) {
					this.calcIsLT200m()
				}
			}
			this.inited = true
		},
		beforeDestroy() {
			this.clearCjRecord()
		}
	}
</script>

<style lang="scss" scoped>
	.z-body {
		background-color: #f5f5f5;
		overflow: auto;
		padding-bottom: 8px;

		::v-deep .title {
			display: flex;
			justify-content: space-between;
			color: black;
			padding: 12px;
		}

		::v-deep .form_group {
			box-sizing: border-box;
			background-color: #fff;
			width: calc(100vw - 16px);
			margin-left: 8px;
			border-radius: 6px;
			border-top: 1px solid #ebebec;
			border-left: 1px solid #ebebec;
			border-right: 1px solid #ebebec;

			.u-form-item__body__left__content {
				padding-left: 16px;
			}

			.u-form-item__body__left__content__required {
				left: 6px;
			}

			&.upload-box {
				.u-upload__button {
					margin: 0;
				}

				.z-upload-title {
					color: gray;
					font-size: 13px;
					margin-bottom: 4px;
				}
			}
		}
	}
</style>